package com.sduept.zj103;

import java.util.HashMap;
import java.util.Map;

import org.tio.client.ClientChannelContext;
import org.tio.client.ReconnConf;
import org.tio.client.TioClient;
import org.tio.client.TioClientConfig;
import org.tio.client.ClientGroupStat;
import org.tio.client.intf.TioClientHandler;
import org.tio.client.intf.TioClientListener;
import org.tio.core.Node;
import org.tio.core.Tio;

import com.sduept.zj103.model.Zj103Protocol;

//@Component
public class Zj103Client {
	public static Node serverNode;
	// handler, 包括编码、解码、消息处理
	public static TioClientHandler tioClientHandler = new Zj103ClientHandler();
	// 事件监听器，可以为null，但建议自己实现该接口，可以参考showcase了解些接口
	public static TioClientListener aioListener = null;
	// 断链后自动连接的，不想自动连接请设为null
	private static ReconnConf reconnConf = new ReconnConf(5000L);
	// 一组连接共用的上下文对象
	public static TioClientConfig clientTioConfig = new TioClientConfig(tioClientHandler, aioListener, reconnConf);
	public static TioClient tioClient;      
	private ClientGroupStat clientGroupContext;
	public static ClientChannelContext clientChannelContext = null;

    private Map<String, Zj103Protocol> clients = new HashMap<>();
    private volatile static Zj103Client clientStarterInstance = null;

    public static Zj103Client getInstance() {
        if(clientStarterInstance == null) {
            synchronized (Zj103Client.class) {
                if(clientStarterInstance == null) {
                    clientStarterInstance = new Zj103Client();
                }
            }
        }
        return clientStarterInstance;
    }
	
	public static void connect(String ip, int port) throws Exception {
		serverNode = new Node(ip, port);
		tioClient = new TioClient(clientTioConfig);
		clientChannelContext = tioClient.connect(serverNode);
	}

	public static boolean isConnected() {
		if(clientChannelContext!=null) {
			return !clientChannelContext.isClosed;
		}
		else {
			return false;
		}
	}


	public static void close() {
		tioClient.stop();
		System.out.println("客户端已经关闭");
	}
	
    public ReconnConf getReconnConf() {
        return reconnConf;
    }

    public void setReconnConf(ReconnConf reconnConf) {
        this.reconnConf = reconnConf;
    }

    public ClientGroupStat getClientGroupContext() {
        return clientGroupContext;
    }

    public void setClientGroupContext(ClientGroupStat clientGroupContext) {
        this.clientGroupContext = clientGroupContext;
    }

    public TioClient getTioClient() {
        return tioClient;
    }

    public void setTioClient(TioClient tioClient) {
        this.tioClient = tioClient;
    }

    public Map<String, Zj103Protocol> getClients() {
        return clients;
    }

    public void setClients(Map<String, Zj103Protocol> clients) {
        this.clients = clients;
    }
}
